import 'reflect-metadata'
import { createConnection, DataSource } from 'typeorm'
import logger from '../utils/logger'
import CONFIG from '../config/index'
import * as path from 'node:path'
import { getEntityFiles, getEntityNames } from '../utils/Typeorm/index'

let entitiesPathsPromise: Promise<string[]> = null // 使用一个 Promise 来存储异步获取的文件路径

// 初始化 entitiesPathsPromise
;(async () => {
  const dirPath = path.resolve(__dirname, '../Entity')
  entitiesPathsPromise = getEntityFiles(dirPath) // 存储 Promise 而不是直接赋值
})()

// 定义一个异步的 TestTypeOrmConnect 函数
export default async function TestTypeOrmConnect() {
  try {
    // 等待 entitiesPathsPromise 解析完成
    const entitiesPaths = await entitiesPathsPromise
    // 创建 TypeORM 连接
    const connection: DataSource = await createConnection({
      ...CONFIG.DATABASE_CONFIG.MYSQL,
      type: 'mysql',
      logging: false,
      entities: entitiesPaths, // 使用解析后的文件路径
      synchronize: true,
    })
    getEntityNames(connection)
    logger.info('TypeOrm连接成功！')
  } catch (error) {
    console.log(error)
  }
}
